package com.jxsd.edu.cn.tools;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.jxsd.edu.cn.tools.DbTool;


//SQL执行模版
public class Template 
{
   //更新数据
   public  int update(String sql,Object[] params)
   {
	   int  count=0;
	   try {
		Connection  conn=DbTool.getConnection();
		PreparedStatement  prestmt=conn.prepareStatement(sql);
		//注入参数
		if(null!=params)
		{
			int i=1;
			for(Object param:params)
			{
				prestmt.setObject(i, param);
				i++;
			}
		}
		count=prestmt.executeUpdate();
		DbTool.close(null, conn, null);
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   return  count;
   }
   /**
    * 存储过程(不带输出值的存储过程)
    * */
   public  void  callUpdate(String sql,Object[] params)
   {
	   CallableStatement  call=null;
	   try {
		Connection  conn=DbTool.getConnection();
		call=conn.prepareCall(sql);
		if(params!=null)
		{
			int i=1;
			for(Object param:params)
			{
				call.setObject(i, param);
				i++;
			}
		}
		call.execute();
	} catch (SQLException e) 
	{
		e.printStackTrace();
	}
   }
   /**
    * 批量更新
    * */
   public   void  batchUpdate(String  sql,List<Object[]>  list)
   {
	   try {
			Connection  conn=DbTool.getConnection();
			conn.setAutoCommit(false);
			PreparedStatement  prestmt=conn.prepareStatement(sql);
			//注入参数
			if(null!=list)
			{
				
				for(Object[] params:list)
				{
					int i=1;
					for(Object  param:params)
					{
						prestmt.setObject(i, param);
						i++;
					}
					prestmt.addBatch();
				}
			}
			prestmt.executeBatch();
			conn.commit();
			//提交
			conn.setAutoCommit(true);
			DbTool.close(null, conn, null);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
   }
}
